package com.ejlchina.tool.fragment.viewpager

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.adolf.androiddemo.R
import com.adolf.androiddemo.databinding.FragmentConfigViewPagerBinding
import com.ejlchina.tool.MainActivity
import com.ejlchina.tool.adapter.ConfigWarningAdapter
import com.ejlchina.tool.base.BaseBindingFragment
import com.ejlchina.tool.bean.BleDeviceBean
import com.ejlchina.tool.bean.ConfigWarningBean
import com.ejlchina.tool.bean.TimeBean
import com.ejlchina.tool.constant.COMMAND_DELAY_TIME_100
import com.ejlchina.tool.constant.COMMAND_DELAY_TIME_200
import com.ejlchina.tool.constant.COMMAND_DELAY_TIME_300
import com.ejlchina.tool.enums.DoorStateEnum
import com.ejlchina.tool.enums.OnOffEnum
import com.ejlchina.tool.enums.SuccessFailEnum
import com.ejlchina.tool.util.COMMAND_AUTH_DOWNWARD
import com.ejlchina.tool.util.COMMAND_AUTH_UPWARD
import com.ejlchina.tool.util.COMMAND_CURRENT_WEIGHT_GET_DOWNWARD
import com.ejlchina.tool.util.COMMAND_CURRENT_WEIGHT_GET_UPWARD
import com.ejlchina.tool.util.COMMAND_DOOR_STATE_GET_DOWNWARD
import com.ejlchina.tool.util.COMMAND_DOOR_STATE_GET_UPWARD
import com.ejlchina.tool.util.COMMAND_DOOR_STATE_SET_DOWNWARD
import com.ejlchina.tool.util.COMMAND_DOOR_STATE_SET_UPWARD
import com.ejlchina.tool.util.COMMAND_ELE_LOCK_DOWNWARD
import com.ejlchina.tool.util.COMMAND_ELE_LOCK_UPWARD
import com.ejlchina.tool.util.COMMAND_FULL_STATE_GET_DOWNWARD
import com.ejlchina.tool.util.COMMAND_FULL_STATE_GET_UPWARD
import com.ejlchina.tool.util.COMMAND_LIGHT_TIME_GET_DOWNWARD
import com.ejlchina.tool.util.COMMAND_LIGHT_TIME_GET_UPWARD
import com.ejlchina.tool.util.COMMAND_LIGHT_TIME_SET_DOWNWARD
import com.ejlchina.tool.util.COMMAND_LIGHT_TIME_SET_UPWARD
import com.ejlchina.tool.util.COMMAND_SWITCH_DOWNWARD
import com.ejlchina.tool.util.COMMAND_SWITCH_UPWARD
import com.ejlchina.tool.util.COMMAND_TEMPERATURE_ALARM_GET_DOWNWARD
import com.ejlchina.tool.util.COMMAND_TEMPERATURE_ALARM_GET_UPWARD
import com.ejlchina.tool.util.COMMAND_TEMPERATURE_ALARM_SET_DOWNLOAD
import com.ejlchina.tool.util.COMMAND_TEMPERATURE_ALARM_SET_UPWARD
import com.ejlchina.tool.util.COMMAND_TEMPERATURE_GET_DOWNWARD
import com.ejlchina.tool.util.COMMAND_TEMPERATURE_GET_UPWARD
import com.ejlchina.tool.util.COMMAND_WEIGHT_CALIBRATION_GET_DOWNWARD
import com.ejlchina.tool.util.COMMAND_WEIGHT_CALIBRATION_GET_UPWARD
import com.ejlchina.tool.util.LOG_TAG
import com.ejlchina.tool.util.SUB_COMMAND_1
import com.ejlchina.tool.util.SUB_COMMAND_2
import com.ejlchina.tool.util.bytearray.intTo32HexStringLE
import com.ejlchina.tool.util.bytearray.readByteArrayBE
import com.ejlchina.tool.util.bytearray.readByteArrayLE
import com.ejlchina.tool.util.bytearray.readInt32LE
import com.ejlchina.tool.util.bytearray.readUInt16LE
import com.ejlchina.tool.util.bytearray.toHexString
import com.ejlchina.tool.util.getBitValueFrom32Bits
import com.ejlchina.tool.util.setOnIntervalClickListener
import com.ejlchina.tool.util.showToast
import com.ejlchina.tool.view.GridItemDecoration
import com.ejlchina.tool.viewmodel.PRIORITY_WRITE_HIGH
import com.huyuhui.fastble.BleManager
import com.huyuhui.fastble.data.BleDevice
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.cancellable
import kotlinx.coroutines.launch
import okhttp3.internal.and
import java.math.BigDecimal
import java.math.RoundingMode
import java.util.Calendar

class ConfigViewPagerFragment(val bleDevice: BleDeviceBean): BaseBindingFragment<FragmentConfigViewPagerBinding>(FragmentConfigViewPagerBinding::inflate) {

    private val configWarningList = arrayListOf<ConfigWarningBean>()
    private lateinit var configWarningAdapter: ConfigWarningAdapter
    private var highWarningTemp = 0
    private var lowWarningTemp = 0
    private var fanControlMode = 0
    private var fanIsOn: Boolean = false
    private var fanOpenTemp = 0
    private var mDoorStateEnum = DoorStateEnum.CLOSE
    private var lightState = 2 //1 打开，2关闭
    private var lightByteArray = byteArrayOf()
    private var isWeightCalibration = false
    private var isLightOn = false
    private var looperJob :Job? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews()
    }

    private fun startLooperFlow(isNeedAuth: Boolean = false) {
        viewLifecycleOwner.lifecycleScope.launch {
            if (isNeedAuth){
                setAuth(false)
            }

            looperJob = launch {
                launch {
                    IntRange(1, Int.MAX_VALUE).asFlow().cancellable().collect{
                        getCommandData(bleDevice, COMMAND_FULL_STATE_GET_DOWNWARD, "", false) //-

                        delay(COMMAND_DELAY_TIME_200)
                        Log.i(LOG_TAG, "1=============================")
                        getCommandData(bleDevice, COMMAND_LIGHT_TIME_GET_DOWNWARD, "", false)

                        delay(COMMAND_DELAY_TIME_200)
                        Log.i(LOG_TAG, "2=============================")
                        getCommandData(bleDevice, COMMAND_TEMPERATURE_ALARM_GET_DOWNWARD, "", false) //hou

                        delay(COMMAND_DELAY_TIME_200)
                        getCommandData(bleDevice,COMMAND_WEIGHT_CALIBRATION_GET_DOWNWARD, "", false)

                        if (it % 2 == 0){
                            Log.i(LOG_TAG, "4=============================")
                            delay(COMMAND_DELAY_TIME_200)
                            getCommandData(bleDevice, COMMAND_TEMPERATURE_GET_DOWNWARD, "", false) //hou

                            if (isWeightCalibration) {
                                delay(COMMAND_DELAY_TIME_300)
                                getCommandData(bleDevice, COMMAND_CURRENT_WEIGHT_GET_DOWNWARD, "", false) //hou
                            }
                        }
                        delay(1500)
                    }
                }

                launch {
                    IntRange(1, Int.MAX_VALUE).asFlow().cancellable().collect{
                        getCommandData(bleDevice, COMMAND_SWITCH_DOWNWARD, "", false) //
                        delay(1000)
                    }
                }

                launch {
                    IntRange(1, Int.MAX_VALUE).asFlow().cancellable().collect{
                        getCommandData(bleDevice, COMMAND_DOOR_STATE_GET_DOWNWARD, "", false)
                        delay(1000)
                    }
                }
            }
        }
    }

    private fun initViews(){
        initConfigWarningData()
        initMacAndVersion()
        initListeners()
        setScanCardTitle()
    }
    private fun initListeners() {
        binding.layoutLock.setOnIntervalClickListener {
            viewLifecycleOwner.lifecycleScope.launch {
                cancelLooperAndClearQueue()
                delay(300)
                getCommandData(bleDevice, COMMAND_ELE_LOCK_DOWNWARD, isNeedShowLoading = false, priority = PRIORITY_WRITE_HIGH)
                delay(200)
                startLooperFlow()
            }
        }
        binding.layoutFan.setOnIntervalClickListener {
            Log.i(LOG_TAG, "Fan Click")
            viewLifecycleOwner.lifecycleScope.launch {
                cancelLooperAndClearQueue()
                delay(300)
                setFanState(if (fanControlMode == 0) 2 else 0)
                delay(200)
                startLooperFlow()
            }
        }

        binding.layoutLight.setOnIntervalClickListener {
            Log.i(LOG_TAG, "Light Click")
            viewLifecycleOwner.lifecycleScope.launch {
                cancelLooperAndClearQueue()
                delay(300)
                setLightState()
                delay(200)
                startLooperFlow()
            }
        }

        binding.btnOpenDoor.setOnIntervalClickListener {
            viewLifecycleOwner.lifecycleScope.launch {
                cancelLooperAndClearQueue()
                delay(300)
                setDoorControlData(mDoorStateEnum == DoorStateEnum.CLOSE)
                when(mDoorStateEnum){
                    DoorStateEnum.OPEN -> {
                        binding.btnOpenDoor.text = DoorStateEnum.CLOSE_DOING.state
                        binding.btnOpenDoor.setBackgroundResource(R.drawable.shape_co_11_so_bbc2f7)
                    }
                    DoorStateEnum.CLOSE -> {
                        binding.btnOpenDoor.text = DoorStateEnum.OPEN_DOING.state
                        binding.btnOpenDoor.setBackgroundResource(R.drawable.shape_co_11_so_bbc2f7)
                    }
                    else -> {}
                }
                delay(200)
                startLooperFlow()
            }
        }
    }


    @SuppressLint("SetTextI18n")
    private fun initMacAndVersion(){
        binding.tvMac.text = "MAC：${bleDevice.bleDevice.mac}"
        binding.tvVersion.text = "固件：${bleDevice.version}"
    }
    private fun initConfigWarningData(){
        if (configWarningList.isEmpty()){
            configWarningList.add(ConfigWarningBean(0,"温度(℃)")) //0
            configWarningList.add(ConfigWarningBean(1,"满溢")) //1
            configWarningList.add(ConfigWarningBean(2,"烟感")) //2
            configWarningList.add(ConfigWarningBean(3,"重量(KG)")) //3
            configWarningList.add(ConfigWarningBean(4,"人感")) // 4
            configWarningList.add(ConfigWarningBean(5,"按钮")) //5
            if (bleDevice.isMachineAntiPinchOn){
                configWarningList.add(ConfigWarningBean(6, "限位防夹"))
            }
            if (bleDevice.isWaterCoverOn){
                configWarningList.add(ConfigWarningBean(7,"水浸"))
            }
        }
        configWarningAdapter = ConfigWarningAdapter(configWarningList)
        binding.recycleView.apply {
            adapter = configWarningAdapter
            layoutManager = GridLayoutManager(requireContext(),3)
            if (itemDecorationCount == 0){
                addItemDecoration(GridItemDecoration(3,1,1))
            }
        }
    }

    private fun setDoorControlData(isOpen: Boolean){
        setCommandData(bleDevice, COMMAND_DOOR_STATE_SET_DOWNWARD, byteArrayOf(if (isOpen) 2.toByte() else 4.toByte()).toHexString(false), isNeedShowLoading = false)
    }

    private fun setAuth(isCancel: Boolean,isNeedShowLoading: Boolean = true){
        setCommandData(bleDevice, COMMAND_AUTH_DOWNWARD, (if (isCancel) SUB_COMMAND_2 else SUB_COMMAND_1) + intTo32HexStringLE(200000),isNeedShowLoading)
    }

    override fun whenReceiveCommand(bleDevice: BleDeviceBean, command: String, dataByteArray: ByteArray) {
        super.whenReceiveCommand(bleDevice,command, dataByteArray)
        if (bleDevice.bleDevice.mac != this@ConfigViewPagerFragment.bleDevice.bleDevice.mac) return
        if (command.startsWith("0402") && command.endsWith("08")){ //扫码头

            setScanDeviceUIData(dataByteArray)
            return
        }
        when(command){
            COMMAND_TEMPERATURE_GET_UPWARD -> {
                refreshWarningData(0,dataByteArray[1].toInt().toString(),dataByteArray[0].toInt() == 0)
            }
            COMMAND_SWITCH_UPWARD -> {
                handleSwitchData(dataByteArray.readByteArrayLE(0,dataByteArray.size))
            }

            COMMAND_ELE_LOCK_UPWARD -> {
                when(dataByteArray[0].toInt()){
                    0 -> setCommonFunctionState(0, isOn = false, isError = true)
                    1 -> setCommonFunctionState(0,true)
                    2 -> setCommonFunctionState(0,false)
                }

            }

            COMMAND_TEMPERATURE_ALARM_GET_UPWARD -> {
                (requireActivity() as MainActivity).saveData(1,this.bleDevice.bleDevice,
                    COMMAND_TEMPERATURE_ALARM_SET_DOWNLOAD,dataByteArray.toHexString(false))
                fanOpenTemp = dataByteArray[3].toInt()
                fanControlMode = dataByteArray[2].toInt()
                lowWarningTemp = dataByteArray[1].toInt()
                highWarningTemp = dataByteArray[0].toInt()
                when(fanControlMode){
                    0 -> {
                        setCommonFunctionState(1, false)
                        fanIsOn = false
                    }
                    1 -> {
                        try {
                            if (configWarningList[0].value.isNotEmpty()) {
                                fanIsOn = configWarningList[0].value.toInt() > fanOpenTemp
                                setCommonFunctionState(1, fanIsOn)
                            }
                        }catch (e: Exception){
                            setCommonFunctionState(1, false)
                        }

                    }
                    2 -> {
                        setCommonFunctionState(1, true)
                        fanIsOn = true
                    }
                }
            }

            COMMAND_TEMPERATURE_ALARM_SET_UPWARD -> {
                fanOpenTemp = dataByteArray[3].toInt()
                fanControlMode = dataByteArray[2].toInt()
                lowWarningTemp = dataByteArray[1].toInt()
                highWarningTemp = dataByteArray[0].toInt()
                try {
                    fanIsOn = fanControlMode == 2 || (fanControlMode == 1 && configWarningList[0].value.toInt() > fanOpenTemp)
                }catch (e: Exception){}
                if (dataByteArray[dataByteArray.size - 1].toInt() == 1){
                    setCommonFunctionState(1,fanControlMode == 2)
                }
            }
            COMMAND_DOOR_STATE_GET_UPWARD -> {
                setDoorStateUI(transformState(dataByteArray[0].toInt()))
                Log.i(LOG_TAG, "门机----》${dataByteArray[0].toInt()}")
                dismissLoading()
            }

            COMMAND_DOOR_STATE_SET_UPWARD -> {
                if (dataByteArray[1].toInt() != 1){
                    showToast("设置失败")
                }
            }

            COMMAND_LIGHT_TIME_GET_UPWARD -> {
                (requireActivity() as MainActivity).saveData(1,this.bleDevice.bleDevice, COMMAND_LIGHT_TIME_SET_DOWNWARD,dataByteArray.toHexString(false))
                lightState = dataByteArray[0].toInt()
                lightByteArray = dataByteArray
                val beginTime = dataByteArray.copyOfRange(2,4).readUInt16LE()
                val endTime = dataByteArray.copyOfRange(4,6).readUInt16LE()
                isLightOn = lightState == 1 || (dataByteArray[1].toInt() == OnOffEnum.ON.value && checkLightTimeInRange(beginTime,endTime))
                setCommonFunctionState(2,isLightOn)
            }

            COMMAND_AUTH_UPWARD -> {

            }

            COMMAND_LIGHT_TIME_SET_UPWARD -> {
                isLightOn = dataByteArray[0].toInt() == 1
                setCommonFunctionState(2,dataByteArray[0].toInt() == 1)
            }

            COMMAND_CURRENT_WEIGHT_GET_UPWARD -> {
                dismissLoading()
                val isStable = dataByteArray[dataByteArray.size - 1].toInt() == 1
                if (isStable){
                    Log.i("TTTTT","重量值-------${dataByteArray.readByteArrayBE(0,4).readInt32LE()}")
                    val number = (dataByteArray.readByteArrayBE(0,4).readInt32LE() / 1000F).toDouble()
                    val num = BigDecimal(number)
                    val roundedNumber = num.setScale(2, RoundingMode.HALF_UP).toFloat()
                    refreshWarningData(3,(if (roundedNumber < 0) 0 else roundedNumber).toString(), true)
                }else {
                    refreshWarningData(3,"-", true)
                }
            }

            COMMAND_WEIGHT_CALIBRATION_GET_UPWARD -> {
                isWeightCalibration = dataByteArray[0].toInt() == SuccessFailEnum.SUCCESS.value
                if (!isWeightCalibration){
                    refreshWarningData(3,"未标定",true)
                }
            }

//            COMMAND_SCAN_CARD_GET_UPWARD -> {
//                binding.tvScanCard.text = if (dataByteArray[0].toInt() == 0) "扫码头" else "刷卡板"
//            }

            COMMAND_FULL_STATE_GET_UPWARD -> {
                setFullState(dataByteArray)
            }
        }
    }

    private fun setScanCardTitle(){
        binding.tvScanCard.text = if (bleDevice.scanOrCard == 0) "扫码头" else "刷卡板"
    }

    private fun setScanDeviceUIData(dataByteArray: ByteArray){
        if (dataByteArray.isEmpty()) return
        var resultText = ""
        if (dataByteArray[0].toInt() == 0){
            resultText = "无扫码头"
        } else {
            val count = dataByteArray[1].toInt()
            if (count < 6) {
                resultText = "未知"
                return
            }
            val originalData = dataByteArray.copyOfRange(2,count + 2)
            if (dataByteArray.size < 4) return
            when (originalData.toHexString(false).substring(0,4)){
                "0202" -> { //扫码头
                    val scanArray = originalData.copyOfRange(4,originalData.size - 1)
                    for (item in scanArray){
                        resultText += (item and 15).toString()
                    }
                }
                "55AA" -> { //刷卡板
                    val cardLong = originalData.copyOfRange(2,originalData.size - 3).toHexString(false)
                    resultText = cardLong.toLong(16).toString().padStart(10,'0')
                }
            }
        }
        binding.etScanCard.setText(resultText)
    }

    private fun formatLightTime(timeValue: Int): TimeBean {
        return TimeBean(timeValue / 60,timeValue % 60)
    }

    private fun checkLightTimeInRange(startTime: Int,endTime: Int): Boolean{
        val hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
        val minute = Calendar.getInstance().get(Calendar.MINUTE)
        val currentTimeMinute = hour * 60 + minute
        return currentTimeMinute in startTime..endTime
    }

    private fun transformState(value: Int): DoorStateEnum{
        return when(value) {
            1 -> DoorStateEnum.OPEN
            2 -> DoorStateEnum.OPEN_DOING
            3 -> DoorStateEnum.CLOSE
            else -> DoorStateEnum.CLOSE_DOING
        }
    }

    private fun handleSwitchData(dataByteArray: ByteArray){
        val isSmokeNormal = getBitValueFrom32Bits(dataByteArray,0) == 0
        val isFullNormal = getBitValueFrom32Bits(dataByteArray,1) == 0
        val isBodyNormal = getBitValueFrom32Bits(dataByteArray,2) == 0
        val isButtonNormal = getBitValueFrom32Bits(dataByteArray,3) == 0
        val isLockNormal = getBitValueFrom32Bits(dataByteArray,4) == 1
        val reuseNormal = getBitValueFrom32Bits(dataByteArray,5) == 0
        val machineAntiPinchNormal = getBitValueFrom32Bits(dataByteArray,6) == 0
        val waterNormal = getBitValueFrom32Bits(dataByteArray,8) == 0
        val smokeValue = if (isSmokeNormal) "正常" else "报警"
        val fullValue = if (isFullNormal) "正常" else "报警"
        val bodyValue = if (isBodyNormal) "无人" else "有人"
        val buttonValue = if (isButtonNormal) "释放" else "按下"
        val lockValue = if (isLockNormal) "开启" else "关闭"
        Log.i(LOG_TAG,"电子锁装置---${isLockNormal}")
        val reuseValue = if (reuseNormal) "关闭" else "打开"
        val machineAntiPinchValue = if (machineAntiPinchNormal) "未触发" else "触发"
        val waterValue = if (waterNormal) "未触水" else "触水"
//        refreshWarningData(1,fullValue,isFullNormal)
        refreshWarningData(2,smokeValue,isSmokeNormal)
        refreshWarningData(4,bodyValue,isBodyNormal)
        refreshWarningData(5, buttonValue, isButtonNormal)
        refreshWarningData(6, machineAntiPinchValue, machineAntiPinchNormal)
        refreshWarningData(7,waterValue,waterNormal)
        setCommonFunctionState(0,isLockNormal)
    }

    private fun refreshWarningData(index: Int, value: String, isNormal: Boolean){
        configWarningList.find { it.index == index }?.let { configWarningBean ->
            configWarningBean.value = value
            configWarningBean.isNormal = isNormal
            configWarningAdapter.notifyItemChanged(index,null)
        }
    }

    private fun setFullState(dataByteArray: ByteArray){
        val type = dataByteArray[0].toInt()
        Log.i(LOG_TAG,"----------type--$type")
        val isFull = dataByteArray[1].toInt() == 1
        val percent = dataByteArray[2].toInt()
        val value = if (type != 1) {
            if (isFull) "溢出" else "正常"
        } else {
            if (isFull) "溢出" else "$percent%"
        }
        configWarningList.find { it.index == 1 }?.let { configWarningBean ->
            configWarningBean.value = value
            configWarningBean.isNormal = !isFull
            configWarningAdapter.notifyItemChanged(1,null)
        }
    }


    private fun setCommonFunctionState(which: Int, isOn: Boolean, isError: Boolean = false){
        val bgResId = if (isOn) R.drawable.shape_co_8_st_1f39ff_so_f2f6ff else R.drawable.shape_co_8_so_ff3b30
        val valueString = if (isOn) "已开启" else "已关闭"
        when(which) {
            0 -> {
                if (isError){
                    binding.layoutLock.setBackgroundResource(R.drawable.shape_co_8_so_ff3b30)
                    binding.tvLockState.text = "未连接"
                }else{
                    binding.layoutLock.setBackgroundResource(bgResId)
                    binding.tvLockState.text = valueString
                }

            }
            1 -> {
                binding.layoutFan.setBackgroundResource(bgResId)
                binding.tvFanState.text = valueString
            }
            2 -> {
                binding.layoutLight.setBackgroundResource(bgResId)
                binding.tvLightState.text = valueString
            }
        }
    }

    private fun setDoorStateUI(doorStateEnum: DoorStateEnum){
        mDoorStateEnum = doorStateEnum
        lifecycleScope.launch {
            when(doorStateEnum){
                DoorStateEnum.OPEN -> {
                    binding.btnOpenDoor.apply {
                        setBackgroundResource(R.drawable.shape_co_11_so_1f39ff)
                        text = doorStateEnum.state
                        isEnabled = true
                    }
                }
                DoorStateEnum.OPEN_DOING -> {
                    binding.btnOpenDoor.apply {
                        setBackgroundResource(R.drawable.shape_co_11_so_bbc2f7)
                        text = doorStateEnum.state
                        isEnabled = false
                    }
                }

                DoorStateEnum.CLOSE -> {
                    binding.btnOpenDoor.apply {
                        setBackgroundResource(R.drawable.shape_co_11_so_1f39ff)
                        text = doorStateEnum.state
                        isEnabled = true
                    }
                }

                DoorStateEnum.CLOSE_DOING -> {
                    binding.btnOpenDoor.apply {
                        setBackgroundResource(R.drawable.shape_co_11_so_bbc2f7)
                        text = doorStateEnum.state
                        isEnabled = false
                    }
                }
            }
        }
    }

    private fun cancelLooperAndClearQueue(){
        looperJob?.cancel()
        BleManager.clearAllQueue(bleDevice.bleDevice)
    }

    private fun setFanState(fanState: Int){
        val byteArray = byteArrayOf(highWarningTemp.toByte(),lowWarningTemp.toByte(),fanState.toByte(),fanOpenTemp.toByte())
        setCommandData(bleDevice, COMMAND_TEMPERATURE_ALARM_SET_DOWNLOAD,byteArray.toHexString(false), isNeedShowLoading = false, priority = PRIORITY_WRITE_HIGH)
    }

    private fun setLightState(){
        val lightDataString = if (isLightOn) "020000000000" else "010000000000"
//        when(lightByteArray[0].toInt()){
//            1 -> lightByteArray[0] = 2.toByte()
//            2  -> lightByteArray[0] = 1.toByte()
//            3 -> lightByteArray[0] = 1.toByte()
//        }

        setCommandData(bleDevice, COMMAND_LIGHT_TIME_SET_DOWNWARD,lightDataString, isNeedShowLoading = false, priority = PRIORITY_WRITE_HIGH)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        Log.i(LOG_TAG,"ConfigViewPagerFragment onDestroyView-${bleDevice.bleDevice}")
        cancelLooperAndClearQueue()
        setAuth(true, isNeedShowLoading = false)
        dismissLoading()

    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i(LOG_TAG,"ConfigViewPagerFragment onDestroy-${bleDevice.bleDevice}")
    }

    override fun onResume() {
        super.onResume()
        showLoading()
        startLooperFlow(true)
        Log.i(LOG_TAG,"ConfigViewPagerFragment resume-${bleDevice.bleDevice}")
    }

    override fun onPause() {
        super.onPause()
        looperJob?.cancel()
        Log.i(LOG_TAG,"ConfigViewPagerFragment onPause-${bleDevice.bleDevice}")
    }

}